#include "EDDemo.h"
#include "vec3.h"

void EDDemo::Initialize(void)
{
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);
    glEnable(GL_CULL_FACE);
 	glEnableClientState(GL_VERTEX_ARRAY);

	// Load the animation
	m_Animation.LoadFromFile("animMesh.msh");
	// Attach the animation to the interpolator
	m_Interpolator.SetAnimation(&m_Animation);

	m_InterpolatorReverse.SetAnimation(&m_Animation);
}

void EDDemo::Shutdown(void)
{
	exit(0);
}

void EDDemo::Display(void)
{    
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
        m_Camera.applyCameraMatrix();

		// Add elapsed time to our interpolator
		m_Interpolator.AddTime(0.001f);

		// Interpolate our animation
		m_Interpolator.Process();

		// Draw the interpolator's current state.
		glVertexPointer(3, GL_FLOAT, 0, &(m_Interpolator.GetCurrKeyFrame()->nodeVec.front()));
		glColor4f(0.5f, 0.8f, 0.8f, 1.0f);
		glDrawArrays(GL_TRIANGLES, 0, m_Interpolator.GetCurrKeyFrame()->numNodes);
		glDisable(GL_DEPTH_TEST);
			glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
				glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
				glDrawArrays(GL_TRIANGLES, 0, m_Interpolator.GetCurrKeyFrame()->numNodes);
			glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);	
		glEnable(GL_DEPTH_TEST);

		glPushMatrix();
			glTranslatef(5.0f, 0.0f, 0.0f);

			m_InterpolatorReverse.AddTime(-0.01f);
			m_InterpolatorReverse.Process();

			// Draw the interpolator's current state.
			glVertexPointer(3, GL_FLOAT, 0, &(m_InterpolatorReverse.GetCurrKeyFrame()->nodeVec.front()));
			glColor4f(0.75f, 0.75f, 0.0f, 1.0f);
			glDrawArrays(GL_TRIANGLES, 0, m_InterpolatorReverse.GetCurrKeyFrame()->numNodes);
			glDisable(GL_DEPTH_TEST);
				glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
					glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
					glDrawArrays(GL_TRIANGLES, 0, m_InterpolatorReverse.GetCurrKeyFrame()->numNodes);
				glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);	
			glEnable(GL_DEPTH_TEST);
		glPopMatrix();


		// Draws the ground.
		float width = 20.0f;
		float y = -5.0f;
		float step = 1.f;
		glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
		for(float x = -width; x <= width; x += step)
		{
			glBegin(GL_TRIANGLE_STRIP);
			for(float z = -width; z <= width; z += step)
			{
				glNormal3f(0.0f, 1.0f, 0.0);
				glVertex3f(x + step, y, z);
				glVertex3f(x, y, z);            
			}
			glEnd();
		}

    glPopMatrix();
    glutSwapBuffers();
}

void EDDemo::Idle(void)
{
	if(GetAsyncKeyState(VK_ESCAPE))
        Shutdown();
    m_Camera.update();
    glutPostRedisplay();
}

void EDDemo::Menu(int value)
{  
    if(value == 0)
        Shutdown(); 
    glutPostRedisplay();
}
